package org.jeecg.modules.system.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by nickyyyyy on 2017/7/10.
 */
public class PageUtils {
    private static final Logger logger = LoggerFactory.getLogger(PageUtils.class);

    /**
     * @param currentPage 当前页数
     * @param pageSize    页面大小
     * @param total       总记录
     * @return 起始索引
     */
    public static long getStartIndex(int currentPage, int pageSize, long total) {
        logger.debug("Entering getStartIndex(page{}, pageSize{}, total{})", currentPage, pageSize, total);
        if (currentPage < 1 || pageSize < 1 || total < 1) {
            return 0;
        }
        int totalPage = (int) (total / pageSize) + (total % pageSize == 0 ? 0 : 1);
        if(currentPage > totalPage)
        {
            currentPage = totalPage;
        }
        long startIndex = (currentPage - 1) * pageSize;
        logger.debug("Leaving getStartIndex(startIndex{})", startIndex);
        return startIndex;
    }

    /**
     * 总页数
     *
     * @param total    总记录数
     * @param pageSize 页面大小
     * @return 总页数
     */
    public static int countPage(int pageSize, long total) {
        if (total < 1 || pageSize < 1) {
            return 0;
        }
        return (int) Math.ceil((double) total / pageSize);
    }
}
